from pymongo import MongoClient
import pymongo
import os
import numpy as np
import sys
import audiofile
import opensmile
smile = opensmile.Smile(
         feature_set=opensmile.FeatureSet.ComParE_2016,
         feature_level=opensmile.FeatureLevel.Functionals,
     )
client = MongoClient(port=27017)
db=client['tiktok_p2']
i=0
#['thriftshop', 'upcycling', 'beautyhacks', 'wrestlemania', 'mystyle', 'superbowllv', 'defrosting', 'ratatouillemusical', 'productivity', 'loveyourinsecurities', 'falldiy', 'glasspainting', 'whereilive', 'foodie', 'nonuancenovember', 'roomtour', 'inverted', 'stemlife', 'fallfashion', 'festivefashion', 'science101', 'lovestory', 'vinylclub', 'homeproject', 'myroutine', 'nbaisback', 'cleantok', 'wishlist', 'imbusyrightnow', 'bakingszn', 'timewarpjump', 'healthyliving', 'plantparent', 'couplethings', 'watchmegrow', 'artmas', 'youwantmore', 'myrecommendation', 'nflplayoffs', 'tiktokdiy', 'blackandproud', 'sidetable', 'passover', 'fitnesslife', 'easydiy', 'stpatricksday', 'myhobby', 'beautyhack', 'holidayvibes', 'unwrapthedeals', 'timewarpwaterfall', 'meditation101', 'feliznavidad', 'onlinedating', 'dinnerparty', 'makeitvogue', 'smallbusiness', 'relationshipstorytime', 'familyimpression', 'dailyvlog', 'worldseries', 'cozyathome', 'animation', 'homebusiness', 'thankstoher', 'ramadanmubarak', 'tiktokfitness', 'coldweather', 'earthday', 'haventseen', 'wip', 'lifestyle', 'learnwithme', 'laughingduet', 'mobilegame', 'coversforlovers', 'gamenight', 'thrifting', 'olympicscountdown', 'imaghost', 'nativefamily', 'zodiacsign', 'passingthephone', 'easyrecipe', 'horrortok', 'hereforrmhc', 'bakedoats', 'puppybowl', 'kissyourpet', 'promszn', 'interiordesign', 'sfxmakeup', 'nbaallstar', 'blackcreatives', 'workingathome', 'skatelife', 'gaminglife', 'graphicdesign', 'tortillatrend', 'christmas2020', 'howbizarre', 'carhacks', 'snowstorm', 'housetour', 'mlkday', 'healthyheart', 'pleasedontgo', 'showupshowoff', 'happyhanukkah', 'perfectdrink', 'neontwin', '90saesthetic', 'holidaycountdown', 'tiktokfashionmonth', 'givingszn', 'royalrumble', 'recordsday', 'ootd', 'meleaving', 'homemade', 'happyhalloween', 'holidaydecor', 'welldone', 'rareaesthetic', 'carsoftiktok', 'foodtiktok', 'heinzhalloween', 'selfimprovement', 'songfacts', 'perfectgifts', 'joblife', 'autismawareness', 'melaninmagic', 'ecohacks', 'mifamilia', 'veteransday', 'thinkingabout', 'learnontiktok', 'seitan', 'growupwithme', 'ohno', 'tabletop', 'colorblast', 'yellow', 'diwali', 'emophase', 'problemsolved', 'neonshadow', 'cartiktok', 'homeimprovement', 'diyprojects', 'careeradvice', 'naturescereal', 'fitnessroutine', 'cleaningtiktok', 'hellowinter', 'bekind', 'gamingtiktok', 'winterbeautytips', 'familyrecipe', 'moneytok', 'tiktokwildlifeday', 'perfectmatch', 'myhaul', 'nbadraft', 'gamingsetup', 'visionboard', 'takeabite', 'wordsofwisdom', 'halloweenlook', '2018vs2021', 'fanedit', 'givethanksnotpranks', 'hyperfixated', 'inlove', 'yougotthis', 'inspirationalquotes', 'homecook', 'feelinggood', 'arabtiktok', 'happyholidays', 'vaccinatedfor', 'wildanimals', 'sheearnedit', 'rnbvibes', 'holidaytiktok', 'homecooked', 'womeninstem', 'dramaticmoments', 'nowlookatthis', 'givingthanks', 'lgbtqhistory', 'healthycooking', 'aprilfools', 'whenwomenwin', 'personalfinance', 'comingofage', 'roundofapplause', 'homeoffice', 'ourtype', 'comfortfood', 'notaperfectperson', 'homecafe', 'holidaycrafts', 'projectcar', 'clingypet', 'seashanty', 'baseballisback', 'holidaytreats', 'planttiktok', 'happyholi', 'foodontiktok', 'catchphrases', 'fetapasta', 'tiktokcars', 'transvisibilityday', '2021affirmations', 'goodmorning', 'greenscreenscan', 'stopasianhate', 'lunarnewyear', 'tiktokfood', 'welcome2021', 'valentinesdiy', 'springvibes', 'hellospring', 'onhold', 'lookbook', 'needtoknow', 'motivationmonday', 'typing', 'homediy', 'stepbystep', 'winterfit', 'happyeaster', 'yearontiktok', 'whatilearned', 'whenwewereyounger', 'weekendvibes', 'somethingyoulearned', 'groupchat', 'itwasntaphase', 'amongus', 'springoutfit', 'ontherunway', 'gamergoals', 'tiktoktailgate', 'athletesoftiktok', 'spookytreats', 'bye2020', 'mycostume', 'dayandnight', 'siblinggoals', 'nhlfaceoff', 'competitivegaming', 'galentinesday', 'albumcover', 'fallguysmoments', 'petsontiktok', 'holidaysourway', 'herstory', 'doctorsoftiktok', 'sabiasque', 'mypfp', 'crowdcheers', 'oscars', 'holidaymusic', 'makeblackhistory', 'fantheory', 'wintersports', 'tiktoktutorial', 'inkdrawing', 'diceroll', 'sehablaespañol', 'raisedby', 'nowruz', 'valentinesday', 'theatrekids', 'cocinando', 'readysetshop', 'skincare101', 'micellarrewind', 'sheesh', 'tipsandtricks', 'puppiesonly', 'halloweenishere', 'stylehacks', 'baseballtiktok', 'marchmadness', 'isthisavailable', 'colddays', 'weirdpets', 'gettheretogether', 'guitartok', 'winterfashion', 'thriftflip']
collist=['thriftshop', 'upcycling', 'beautyhacks', 'wrestlemania', 'mystyle', 'superbowllv', 'defrosting', 'ratatouillemusical', 'productivity', 'loveyourinsecurities', 'falldiy', 'glasspainting', 'whereilive', 'foodie', 'nonuancenovember', 'roomtour', 'inverted', 'stemlife', 'fallfashion', 'festivefashion', 'science101', 'lovestory', 'vinylclub', 'homeproject', 'myroutine', 'nbaisback', 'cleantok', 'wishlist', 'imbusyrightnow', 'bakingszn', 'timewarpjump', 'healthyliving', 'plantparent', 'couplethings', 'watchmegrow', 'artmas', 'youwantmore', 'myrecommendation', 'nflplayoffs', 'tiktokdiy', 'blackandproud', 'sidetable', 'passover', 'fitnesslife', 'easydiy', 'stpatricksday', 'myhobby', 'beautyhack', 'holidayvibes', 'unwrapthedeals', 'timewarpwaterfall', 'meditation101', 'feliznavidad', 'onlinedating', 'dinnerparty', 'makeitvogue', 'smallbusiness', 'relationshipstorytime', 'familyimpression', 'dailyvlog', 'worldseries', 'cozyathome', 'animation', 'homebusiness', 'thankstoher', 'ramadanmubarak', 'tiktokfitness', 'coldweather', 'earthday', 'haventseen', 'wip', 'lifestyle', 'learnwithme', 'laughingduet', 'mobilegame', 'coversforlovers', 'gamenight', 'thrifting', 'olympicscountdown', 'imaghost', 'nativefamily', 'zodiacsign', 'passingthephone', 'easyrecipe', 'horrortok', 'hereforrmhc', 'bakedoats', 'puppybowl', 'kissyourpet', 'promszn', 'interiordesign', 'sfxmakeup', 'nbaallstar', 'blackcreatives', 'workingathome', 'skatelife', 'gaminglife', 'graphicdesign', 'tortillatrend', 'christmas2020', 'howbizarre', 'carhacks', 'snowstorm', 'housetour', 'mlkday', 'healthyheart', 'pleasedontgo', 'showupshowoff', 'happyhanukkah', 'perfectdrink', 'neontwin', '90saesthetic', 'holidaycountdown', 'tiktokfashionmonth', 'givingszn', 'royalrumble', 'recordsday', 'ootd', 'meleaving', 'homemade', 'happyhalloween', 'holidaydecor', 'welldone', 'rareaesthetic', 'carsoftiktok', 'foodtiktok', 'heinzhalloween', 'selfimprovement', 'songfacts', 'perfectgifts', 'joblife', 'autismawareness', 'melaninmagic', 'ecohacks', 'mifamilia', 'veteransday', 'thinkingabout', 'learnontiktok', 'seitan', 'growupwithme', 'ohno', 'tabletop', 'colorblast', 'yellow', 'diwali', 'emophase', 'problemsolved', 'neonshadow', 'cartiktok', 'homeimprovement', 'diyprojects', 'careeradvice', 'naturescereal', 'fitnessroutine', 'cleaningtiktok', 'hellowinter', 'bekind', 'gamingtiktok', 'winterbeautytips', 'familyrecipe', 'moneytok', 'tiktokwildlifeday', 'perfectmatch', 'myhaul', 'nbadraft', 'gamingsetup', 'visionboard', 'takeabite', 'wordsofwisdom', 'halloweenlook', '2018vs2021', 'fanedit', 'givethanksnotpranks', 'hyperfixated', 'inlove', 'yougotthis', 'inspirationalquotes', 'homecook', 'feelinggood', 'arabtiktok', 'happyholidays', 'vaccinatedfor', 'wildanimals', 'sheearnedit', 'rnbvibes', 'holidaytiktok', 'homecooked', 'womeninstem', 'dramaticmoments', 'nowlookatthis', 'givingthanks', 'lgbtqhistory', 'healthycooking', 'aprilfools', 'whenwomenwin', 'personalfinance', 'comingofage', 'roundofapplause', 'homeoffice', 'ourtype', 'comfortfood', 'notaperfectperson', 'homecafe', 'holidaycrafts', 'projectcar', 'clingypet', 'seashanty', 'baseballisback', 'holidaytreats', 'planttiktok', 'happyholi', 'foodontiktok', 'catchphrases', 'fetapasta', 'tiktokcars', 'transvisibilityday', '2021affirmations', 'goodmorning', 'greenscreenscan', 'stopasianhate', 'lunarnewyear', 'tiktokfood', 'welcome2021', 'valentinesdiy', 'springvibes', 'hellospring', 'onhold', 'lookbook', 'needtoknow', 'motivationmonday', 'typing', 'homediy', 'stepbystep', 'winterfit', 'happyeaster', 'yearontiktok', 'whatilearned', 'whenwewereyounger', 'weekendvibes', 'somethingyoulearned', 'groupchat', 'itwasntaphase', 'amongus', 'springoutfit', 'ontherunway', 'gamergoals', 'tiktoktailgate', 'athletesoftiktok', 'spookytreats', 'bye2020', 'mycostume', 'dayandnight', 'siblinggoals', 'nhlfaceoff', 'competitivegaming', 'galentinesday', 'albumcover', 'fallguysmoments', 'petsontiktok', 'holidaysourway', 'herstory', 'doctorsoftiktok', 'sabiasque', 'mypfp', 'crowdcheers', 'oscars', 'holidaymusic', 'makeblackhistory', 'fantheory', 'wintersports', 'tiktoktutorial', 'inkdrawing', 'diceroll', 'sehablaespañol', 'raisedby', 'nowruz', 'valentinesday', 'theatrekids', 'cocinando', 'readysetshop', 'skincare101', 'micellarrewind', 'sheesh', 'tipsandtricks', 'puppiesonly', 'halloweenishere', 'stylehacks', 'baseballtiktok', 'marchmadness', 'isthisavailable', 'colddays', 'weirdpets', 'gettheretogether', 'guitartok', 'winterfashion', 'thriftflip']

for col in collist[:1]:
    for item in db[col].find():
        if os.path.exists('E:\\wav_pi\\' + item['_id'] + '.wav'):
            signal, sampling_rate = audiofile.read('E:\\wav_pi\\' + item['_id'] + '.wav')
        else:
            os.system('ffmpeg -i E:\\Tiktok\\Hashtag\\' + col + '\\' + item['_id'] + '.mp4 E:\\wav_pi\\' + item[
                '_id'] + '.wav')
            signal, sampling_rate = audiofile.read('E:\\wav_pi\\' + item['_id'] + '.wav')

        for fn in range(10):
            if len(item['frame_level']['f'+str(fn)]['audio'])>0:
                continue
            k=smile.process_signal(signal[:,(len(signal[1])//10)*fn:(len(signal[1])//10)*(fn+1)],sampling_rate=sampling_rate)
            k=k.values.tolist()[0]
            #db[col].update_one({'_id': item['_id']}, {'$set':{'video_feature.audio.yamnet':k}})
            db[col].update_one({'_id':  item['_id']}, {'$set': {'frame_level.f' + str(fn)+'.audio': k}})
            print('update success ',col,item['_id'])
            i += 1


